<?php
class Admini_JobController extends Uuch_BaseController{    
    
    public function init() {
    }
    
    public function indexAction()
    {
        $jobList = Application_Model_JobFactory::getJobList();
        foreach ($jobList as $jobVal) {
            $jobItem = Application_Model_JobFactory::createJobExecute($jobVal);
            $jobItem->Execute($jobVal);
        }
        exit;
    }
    
    public function indexoneAction()
    {
        $id = $this->getSafeParam("id");
        $jobLoad = Application_Model_JobFactory::getJobLoad($id);
        $jobItem = Application_Model_JobFactory::createJobExecute($jobLoad);
        $jobLoad->Operator = Uuch_Util::getUserNikeName();
        $jobItem->Execute($jobLoad);
        $this->json(1);
    }
    
    
    /**
     * 获取淘宝订单的物流信息
     */
    public function  taobaoinfoAction()
    {
        $orderItem = Application_Model_Order::getAllOrder();
        //header("Content-type:text/html;charset=utf-8");
        //var_dump($orderItem);
        $taobao = new Uuch_Reader_TaobaoReader();
        $arrSign = Application_Model_Taobaoapi::getSignAll();
        //var_dump($arrSign);
        foreach ($orderItem as  $orderval) {
            //echo $orderval->procureNo.'<br>';
            $taobaoid = substr($orderval->procureNo, -4);
            if(!in_array($taobaoid, $arrSign)){
                continue;
            }
            $result = $taobao->taobaowlxx($orderval->procureNo,'jobController/taobaoinfo');
            //var_dump($result);
            if($result && $result->code){
                continue;
            }
            if(!$result->trade->orders){
                continue;
            }
            $logistics_company = $result->trade->orders->order;
            if (!$logistics_company) {
                $logistics_company = $result->trade->orders->order[1];
            }
            if(!$logistics_company) {
                continue;
            }
            foreach ($logistics_company->logistics_company as $key => $nameval) {
                $shipresult = Application_Model_shipType::getByName($nameval);
                if ($shipresult) {
                    $orderval->logistics = $shipresult->id;
                    continue;
                }
                $orderval->logistics = 181; 
            }
            $invoice_no = $logistics_company->invoice_no;
            if (!$invoice_no) {
                $invoice_no = $logistics_company->invoice_no;
            }
            if (!$invoice_no) {
                continue;
            }
            foreach ($invoice_no as $key => $noval) {
                $orderval->logisticsNo = $noval;
            }
            $orderval->status = Application_Model_Order::STATUS_SELLER_SENDED;
            $orderval->dateConfrim = date("Y-m-d H:i:s");
            $orderval->save();    
            Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $orderval->id, $orderval->operator, $orderval->getStatusNames(), Application_Model_Tracking::User_Block, $orderval->status, date("Y-m-d H:i:s"));
        }
        Application_Model_Operate::addOperate(0, null, null, "更新淘宝订单的物流信息", null);
        echo 1;
        exit;
    }
    /**
     * 淘宝物流信息测试方法
     */
    public function  taobaoinfooneAction()
    {
        $id = $this->getSafeParam("id");
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $orderItem = Application_Model_Order::load($id);
        $taobao = new Uuch_Reader_TaobaoReader();
        $arrSign = Application_Model_Taobaoapi::getSignAll();
        $taobaoid = substr($orderItem->procureNo, -4);
        if(in_array($taobaoid, $arrSign)){
            $result = $taobao->taobaowlxx($orderItem->procureNo,'jobController/taobaoinfoone');
            var_dump($result);
            echo "<br>";
            if($result){
                if ($result->code) {
                    echo $orderItem->procureNo." sessionkey已过期<br>";
                } else {
                    var_dump($result->trade->orders->order[0]);
                    echo "<br>";
                    var_dump($result->trade->orders->order[1]);
                    echo "<br>";
                }
            }
        }else{
            echo $orderval->procureNo."不是淘宝订单<br>";
        }
        
        exit;
    }
    /**
     * 延长淘宝sessionkey有效期
     */
    public function extendtaobaoAction()
    {
        $taobao = new Uuch_Reader_TaobaoReader();
        $taobao->getTaobaoToken();
        exit;
    }
    
    /**
     * 代购超期
     */
    public function outtimeorderAction()
    {
        $orderUnItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_UNSEND);
        if($orderUnItem){
            foreach ($orderUnItem as $orderVal) {
                if($orderVal->datePaid < date("Y-m-d H:i:s", strtotime(" -2 day "))){
                    $orderVal->status = Application_Model_Order::STATUS_OUTTIME_UNSEND;
                    $orderVal->save();
                }
            }
        }
        $orderSubItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_SUBSCRIBE);
        if($orderSubItem){
            foreach ($orderSubItem as $orderSubVal) {
                if($orderSubVal->dateShip < date("Y-m-d H:i:s", strtotime(" -2 day "))){
                    $orderSubVal->status = Application_Model_Order::STATUS_OUTTIME_UNSEND;
                    $orderSubVal->save();
                }
            }
        }
        $this->outInStore();
    }
    private function outInStore()
    {
        $orderSellerItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_SELLER_SENDED);
        foreach ($orderSellerItem as $orderSellerVal) {
            $storeItem = Application_Model_StoreItem::getbyLogistics($orderSellerVal->logisticsNo);
            if($storeItem){
                $orderSellerVal->status = Application_Model_Order::STATUS_INSTORE;
                $orderSellerVal->save();
                continue;
            }
            $this->AnalysisOutInStore($orderSellerVal);
        }
        $orderOutTimeItem = Application_Model_Order::getOrderAllByStatus(Application_Model_Order::STATUS_OUTTIME_INSTORE);
        foreach ($orderOutTimeItem as $orderSellerVal) {
            $storeItem = Application_Model_StoreItem::getbyLogistics($orderSellerVal->logisticsNo);
            if($storeItem){
                $orderSellerVal->status = Application_Model_Order::STATUS_INSTORE;
                $orderSellerVal->save();
                continue;
            }
            $this->AnalysisOutInStore($orderSellerVal);
        }
        echo 1;
        exit;
    }
    private function AnalysisOutInStore($orderSellerVal)
    {
        if($orderSellerVal->consignTime != "" && $orderSellerVal->consignTime != null && $orderSellerVal->consignTime != "0000-00-00 00:00:00.000000" && $orderSellerVal->consignTime != "0000-00-00 00:00:00"){
            if($orderSellerVal->consignTime < date("Y-m-d H:i:s", strtotime(" -5 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
                $orderSellerVal->save();
            }
            if($orderSellerVal->consignTime < date("Y-m-d H:i:s", strtotime(" -10 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
                $orderSellerVal->save();
            }
            return true;
        }
        if($orderSellerVal->dateShip != "" && $orderSellerVal->dateShip != null && $orderSellerVal->dateShip != "0000-00-00 00:00:00.000000" && $orderSellerVal->dateShip != "0000-00-00 00:00:00"){
            if($orderSellerVal->dateShip < date("Y-m-d H:i:s", strtotime(" -5 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
                $orderSellerVal->save();
            }
            if($orderSellerVal->dateShip < date("Y-m-d H:i:s", strtotime(" -10 day "))){
                $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
                $orderSellerVal->save();
            }
            return true;
        }
        if($orderSellerVal->datePaid < date("Y-m-d H:i:s", strtotime(" -5 day ")) && $orderSellerVal->datePaid != "0000-00-00 00:00:00.000000" && $orderSellerVal->datePaid != "0000-00-00 00:00:00"){
            $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_INSTORE;
            $orderSellerVal->save();
        }
        if($orderSellerVal->datePaid < date("Y-m-d H:i:s", strtotime(" -10 day ")) && $orderSellerVal->datePaid != "0000-00-00 00:00:00.000000" && $orderSellerVal->datePaid != "0000-00-00 00:00:00"){
            $orderSellerVal->status = Application_Model_Order::STATUS_OUTTIME_FIN;
            $orderSellerVal->save();
        }
        return true;
    }    
    /**
     * 淘宝返利测试地址
     */
    public function taobaotopurlAction()
    {
        $id = $this->getSafeParam("id");
        $order = Application_Model_Order::load($id);
        $orderItem = $order->getItems();
        foreach ($orderItem as $orVal) {
            $product = Application_Model_Product::load($orVal->productId);
            if (strpos($product->url, "taobao") > 0 || strpos($product->url, "tmall") > 0) {
                $taobalReader = new Uuch_Reader_TaobaoReader();
                $topUrl = $taobalReader->getOneTopUrl($product->name, $product->url);
                if ($topUrl != NULL) {
                    echo "返利地址为：". $topUrl;
                } else {
                    echo "没有获取到返利地址";
                }
            } else {
                echo "不是淘宝订单";
            }
        }
        exit;
    }
    /**
     * paypal流水号信息 
     */
    public function allpaypalAction()
    {
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $start_time = time() - 3600*24*2;
        $iso_start = date('Y-m-d\T00:00:00\Z', $start_time);
        $nvpStr = "&STARTDATE=$iso_start";
        $end_time = time() - 3600*24;
        $iso_end = date('Y-m-d\T24:00:00\Z', $end_time);
        $nvpStr.="&ENDDATE=$iso_end";

        $paypal = new Uuch_PayPal();
        $resArray = $paypal->hash_call("TransactionSearch", $nvpStr);
        
        $count = 0;
        while (isset($resArray["L_TRANSACTIONID" . $count])) {
            $count++;
        }
        $ID = 0;
        
        while ($count > 0) {
            $paybillItem = Application_Model_PayBill::bypayIdTxnId(Application_Model_PayBill::PAY_PAYPAL, $resArray["L_TRANSACTIONID" . $ID]);
            if($paybillItem){
                continue;
            }
            $this->AnalysisPayLog($resArray["L_TRANSACTIONID" . $ID], $resArray["L_STATUS" . $ID]);
            
            $paypalLogItem = new Application_Model_PaypalLog();
            $paypalLogItem->TxnId = $resArray["L_TRANSACTIONID" . $ID];
            $paypalLogItem->DateCreated = date("Y-m-d H:i:s",  strtotime($resArray["L_TIMESTAMP" . $ID]));
            $paypalLogItem->PaypalName = $resArray["L_NAME" . $ID];
            $paypalLogItem->Amount = $resArray["L_AMT" . $ID];
            $paypalLogItem->PaypalStatus = $resArray["L_STATUS" . $ID];
            $paypalLogItem->PaypalEmail = isset($resArray["L_EMAIL".$ID])?$resArray["L_EMAIL".$ID]:"";
            $paypalLogItem->FeeAmt = $resArray["L_FEEAMT" . $ID];
            $paypalLogItem->Status = Application_Model_PaypalLog::Status_Default;
            $paypalLogItem->save();
            
            $count--;
            $ID++;
        }
        exit;
    }
    private function AnalysisPayLog($payNo,$status)
    {
        $payLogItem = Application_Model_PaypalLog::byTxnId($payNo);
        if($payLogItem){
            if($payLogItem->paypalStatus == $status){
                return true;
            }
            $payLogItem->IsDel = 1;
            $payLogItem->save();
            return true;
        }
        echo "Paypal流水号：".$payNo." 在用户支付记录中没有找到，请进Paypal日志中操作。<br>";
        return true;
    }
    /**
     * 国际运单超期
     */
    public function outtimebillAction()
    {
        $billOutItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Outstorage);
        foreach ($billOutItem as $billOutval){
            $single = Application_Model_Single::bySingle($billOutval->agentNo);
            if($single){
                continue;
            }
            if ($billOutval->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                $billOutval->interior = Application_Model_wayBillItem::Interior_OverSystem;
                $billOutval->save();
            }
        }
        echo "上系统超期的运单检查完成<br>";
        $billSystemItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_System);
        foreach ($billSystemItem as $billSystemvalue) {
            if ($billSystemvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                $billSystemvalue->interior = Application_Model_wayBillItem::Interior_Oversingleno;
                $billSystemvalue->save();
            }
        }
        echo "转到超期的运单检查完成<br>";
        $billTransportationItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Singleno);
        foreach ($billTransportationItem as $billTransportationvalue) {
            if ($billTransportationvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -2 day "))) {
                $billTransportationvalue->interior = Application_Model_wayBillItem::Interior_OutTransportation;
                $billTransportationvalue->save();
            }
        }
        echo "上网超期的运单检查完成<br>";
        $billSingleItem = Application_Model_wayBillItem::getDelayAll(Application_Model_wayBillItem::Interior_Transportation);
        foreach ($billSingleItem as $billSingvalue) {
            $expresspriceItem = Application_Model_ExpressPrice::getPriceByExpressAndCity($billSingvalue->expressId, $billSingvalue->state);
            if(!$expresspriceItem){
                continue;
            }
            $times = explode("~", $expresspriceItem->times);
            if ($billSingvalue->dateSend < date("Y-m-d H:i:s", strtotime(" -$times[1] day "))) {
                $billSingvalue->interior = Application_Model_wayBillItem::Interior_Overachieve;
                $billSingvalue->save();
            }
        } 
        echo "完成超期的运单检查完成<br>";
        exit;
    }
    /**
     * 国际运单完成
     */
    public function deliveredAction()
    {
        $billOutItem = Application_Model_wayBillItem::getOutDelivered();
        foreach ($billOutItem as $outVal) {
            $no = $outVal->Logistics;
            $express = $outVal->getExpressBy();
            if(($express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI100  || $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK) 
                    && $this->AnalysisExpress($express, $no)){
                $outVal->ActivityConsumeExchangeScore();
                $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                $outVal->save();
                $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
            }else if($express->TrackType == Application_Model_Express::TRACK_TYPE_3TH && $this->AnalysisAchieve($no)){
                $outVal->ActivityConsumeExchangeScore();
                $outVal->Status = Application_Model_wayBillItem::STATUS_Complated;
                $outVal->Interior = Application_Model_wayBillItem::Interior_Achieve;
                $outVal->save();
                $outVal->addBillLog(Application_Model_wayBillItem::Interior_Achieve);
                echo $outVal->BillNO."已经完成发货，用户已经收货！<br>";
            }   
        }
        echo "国际运单完成签收检查完成";
        exit;
    }
    private function AnalysisExpress($express,$no)
    {
        $type = $express->TrackNo;
        $isUrl = $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK?0:1;
        if(!$isUrl) {
            return false;
        }
        $content = Uuch_Util::express($type, $no);
        $result = strip_tags($content);
        if(strpos($result,":00Delivered") > 0 || strpos($result,":00Delivered") === 0) {
            return true;
        } 
        if(strpos($result,"已派送并签收") > 0 || strpos($result,"已派送并签收") === 0) {
            return true;
        } 
        if(strpos($result,"投递并签收") > 0 || strpos($result,"投递并签收") === 0) {
            return true;
        }
        return false;
    }
    private function AnalysisAchieve($no)
    {
        $sg = new Uuch_SpeedPostAPI();
        $result = $sg->query($no);
        if(!$result){
            return false;
        }
        foreach ($result as  $item){
            if($item->status == "Delivered"){
                return true;
            }
            return false;
        }
        return false;
    }
    
    public function eubpdfAction() {
        $id = $this->getSafeParam("id");
        Uuch_Tcpdf::printPDFByBillId("X4", $id);
        exit;
    }
    
    public function orderdataAction() {
        ini_set('memory_limit', '512M');
        $dataTime = date("Y-m-d");
        $report = new Application_Model_DbTable_Report();
        $orderItem = $report->OrderData("all",$dataTime);
        $orderNewItem = $report->OrderData("new",$dataTime);
        $orderOldItem = $report->OrderData("old",$dataTime);
        Application_Model_Data::DisposeOrderData($dataTime,$orderItem,$orderNewItem,$orderOldItem);
        echo 1;
        exit;
    }
    
    public function waydataAction() {
        ini_set('memory_limit', '512M');
        $dataTime = date("Y-m-d");
        $report = new Application_Model_DbTable_Report();
        $wayItem = $report->WayData("all",$dataTime);
        $wayNewItem = $report->WayData("new",$dataTime);
        $wayOldItem = $report->WayData("old",$dataTime);
        Application_Model_Data::DisposeWayData($dataTime, $wayItem, $wayNewItem, $wayOldItem);
        echo 1;
        exit();
    }
    
    public function storedataAction() {
        ini_set('memory_limit', '512M');
         $dataTime = date("Y-m-d");
        $report = new Application_Model_DbTable_Report();
        $storeItem = $report->StoreData("all",$dataTime);
        $storeNewItem = $report->StoreData("new",$dataTime);
        $storeOldItem = $report->StoreData("old",$dataTime);
        Application_Model_Data::DisposeStoreData($dataTime, $storeItem, $storeNewItem, $storeOldItem);
        echo 1;
        exit();
    }
    
    public function userdataAction() {
        ini_set('memory_limit', '512M');
        $dataTime = date("Y-m-d");
        $userSearch = new Application_Model_Filter_UserSearch();
        $userSearch->dateselect = "regedit";
        $userSearch->starttime = $dataTime;
        $userSearch->endtime = $dataTime;
        $userSearch->isUniteLogin = 1;
        $userItem  = Application_Model_User::ByAll($userSearch);
        Application_Model_Data::disposeUserData($dataTime,$userItem);
        echo 1;
        exit();
    }
    
    public function recommendAction()
    {
        $wayMaxId = Application_Model_OptionItem::getSearch("recommendMaxWayId");
        $recommendWayItem = Application_Model_wayBillItem::ByMaxId($wayMaxId->Myvalue);
        foreach ($recommendWayItem as $recommendWayVal) {
            $recommendItem = Application_Model_Recommend::ByUserIdReUserId($recommendWayVal->UserId, null);
            if(!$recommendItem){
                continue;
            }
            $rewardItem = new Application_Model_Reward();
            $rewardItem->UserId = $recommendWayVal->UserId;
            $rewardItem->BillNo = $recommendWayVal->BillNo;
            $rewardItem->Money = "0.00";
            $rewardItem->Rebate = "0.00";
            $rewardItem->ReUserId = $recommendItem->ReUserId;
            $rewardItem->IsAbled = Application_Model_Reward::IsAbled_Unfinished;
            $rewardItem->CreateTime = date("Y-m-d H:i:s");
            $rewardItem->save();
            echo "国际运单".$recommendWayVal->BillNo."返利<br>";
        }
        $maxId = Application_Model_wayBillItem::MaxId();
        $wayMaxId->Myvalue = $maxId;
        $wayMaxId->save();
        
       $unRewardItem = Application_Model_Reward::ByIsAbled(Application_Model_Reward::IsAbled_Unfinished);
       foreach ($unRewardItem as $unRewardVal) {
           $waybillItem = Application_Model_wayBillItem::bybillNo($unRewardVal->BillNo);
           if($waybillItem && $waybillItem->Interior == Application_Model_wayBillItem::Interior_Achieve) {
               $unRewardVal->Money = $waybillItem->LastMoney;
               $unRewardVal->Rebate = $waybillItem->LastMoney*(Application_Model_Reward::Rebates_Proportion);
               $unRewardVal->IsAbled = Application_Model_Reward::IsAbled_Complete;
               $unRewardVal->save();
               echo "国际运单".$waybillItem->BillNo."返利可以领取<br>";
           }
       }
       exit;
    }

    public function getFreeDays($dateInStore) {
            $start = time();
            $end = strtotime($dateInStore . ' + 3 month');
            $days = (int)(($end - $start) / 86400);       
            return $days > 90 ? 90 : $days;
    }

    //过期物品扫描通知
    public function emailAction()
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');  
        $db = $bootstrap->getResource('db');
        $now = date('Y-m-d h:i:s',time()) ;
        $up_dq = date('Y-m-d', strtotime('-12 month'));
        $sjc = date('Y-m-d',strtotime('- 3 month + 1 week ',time()));
        $sjc2 = date('Y-m-d',strtotime(' + 2 week ',time()));


        $userlist = $db->fetchAll(
             "SELECT u.email,u.nikename FROM `uuch_storeitem` AS s left join uuch_user as u on u.id = s.userid left join uuch_account as a on a.id = s.userid ".   
             " WHERE  isdelete = '0' AND s.state = '1' AND (a.dateUp < '$up_dq' || a.dateUp is null)  AND s.dateOver > '$now' AND s.dateInStore like '%$sjc%'  group by userid"
         );

        $userlist2 = $db->fetchAll(
             "SELECT u.email,u.nikename FROM `uuch_storeitem` AS s left join uuch_user as u on u.id = s.userid ".   
             " WHERE  isdelete = '0' AND s.state = '1' AND  s.dateOver like '%$sjc2%'  group by userid"
         ); 

        $title = '免费仓储到期通知';
        $content = '尊敬的用户：
                    悠奇免费保管期限为三个月，保管日期自包裹被签收当天开始计算，现即将到期。
                    超过保管期限仍未出运的物品将收取0.5元/天的保管费用(以物品编号为单位)，
                    超过半年仍未出运的物品，悠奇将直接移出库位，并不接受对此物品的任何操作。';

        $title2 = '仓储到期通知';
        $content2 = '尊敬的用户：
                    您的仓储期限即将超过半年，还有两周到期，如果不提交运单，
                    悠奇将直接移出库位，并不接受对此物品的任何操作，有疑问请联系悠奇客服！';

        if($userlist){
            foreach ($userlist as $k => $value) {
                $receive = array('email' => $value['email'], 'name' => $value['email']);
                Uuch_Mail::SendMail($title, $content, $receive);        
            }         
        }

        if($userlist2){
            foreach ($userlist2 as $k => $value) {
                $receive = array('email' => $value['email'], 'name' => $value['email']);
                Uuch_Mail::SendMail($title2, $content2, $receive);        
            }         
        }

        exit;
    }

    //年费邮件通知 频繁发送邮箱受限
    public function emailtestAction()
    {   
        ini_set('max_execution_time','0');
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');  
        $db = $bootstrap->getResource('db');
        $userlist = $db->fetchAll(
             "SELECT email,nikename FROM `uuch_user` WHERE  userType = '0' AND email!='' AND id <= 49252 order by id desc limit 430,50"
         );
        foreach ($userlist as $k => $value) {
            echo $value['email'].",";
        }
        exit;
        //var_dump($userlist);exit;
        $title = '年费充值 惊喜不断';
        $content = '亲爱的悠粉们，大家好！

                      为了感谢广大悠粉长期以来的支持，悠奇特推出年费会员服务，年费用户将享受所有国际运单9.8折优惠以及其他多项专属服务!
                详情请戳：http://www.uuch.com/cms/noticenew/noticecontent/titleId/65/typeId/1    
                充值请点击：http://www.uuch.com/myfund/index/up/


                深圳市悠奇电子商务有限公司';
        $pregEmail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        header("Content-type: text/html; charset=utf-8");   
        foreach ($userlist as $k => $value) {
            if(preg_match($pregEmail, $value['email'])){
                $receive = array('email' => $value['email'], 'name' => $value['email']);
                if(Uuch_Mail::SendMail($title, $content, $receive)){
                    echo $value['email']."发送第<span style='color:red;'>".$k."</span>条成功!<br>";
                }else{
                    echo $value['email']."<span style='color:red;'>发送第".$k."条失败!</span><br>"; 
                    continue;   
                }

            }else{
                echo $value['email']."<span style='color:red;'>第".$k."邮箱格式错误!</span><br>";
            }
            //24761
        }
        
        // $receive = array('email' => '527413987@qq.com', 'name' => '527413987@qq.com');
        // if(Uuch_Mail::SendMail($title, $content, $receive)){
        //     echo '成功123';
        // }
        exit;
    }   


    //增加库位
    public function insertAction()
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');  
        $db = $bootstrap->getResource('db');
        //echo 123;exit;
        $table = 'uuch_storelocation';// 插入数据的数据表
        //$db = $this->getAdapter();
        //echo 666;exit;
        $sj = date('Y-m-d H:i:s',time());
        // 以"列名"=>"数据"的格式格式构造插入数组,插入数据行

        // 插入数据行并返回插入的行数
        for ($i=10; $i<=59; $i++) {
            $row = array (
            'userId' => NULL,
            'locationNo' => 'A5-'.$i,
            'status' => '0',
            'library' => 'A5',
            'datecreated' => $sj,
            );
            $rows_affected = $db->insert($table, $row);
        } 
        // 最后插入的数据id
        echo $last_insert_id = $db->lastInsertId();
        exit;
    } 

    //发送新会员礼包
    public function couponAction()
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');  
        $db = $bootstrap->getResource('db');

        $userlist = $db->fetchAll(
             "SELECT u.id FROM uuch_waybill as w left join uuch_user as u on u.id = w.userId  where u.datecreated >= '2016-07-01' and u.datecreated <= '2016-08-11' and w.status != -1 group by w.userId"
         );
        $arrstr = '';
        foreach ($userlist as $k => $value) {

            $arrstr .= $value['id'].',';
        }
        $arrstr .= 48214; 
        //var_dump($arrstr);exit;

        $userlist2 = $db->fetchAll(
             "SELECT id FROM `uuch_user` where datecreated >= '2016-07-01' and datecreated <= '2016-08-11' and userType = '0' and id not in($arrstr) order by id desc"
         );

        //var_dump($userlist2);exit;
        
        $type = Application_Model_Coupon::Type_SatisfyReduce;
        $scope = Application_Model_Coupon::Scope_Waybill;
        $batchNo = 'DiscountCouponAll';
        $dateExpired = '2016-09-15';

        foreach ($userlist2 as $k => $value) {
            Application_Model_Coupon::addCoupon($value['id'], $dateExpired, null, 300, 30, null, $type, $scope, date("Y-m-d H:i:s"), $batchNo, "新会员礼包");
        }



        echo '成功！';
        exit;
    } 

 //16年至今运单情况
 public function tjAction()
    {
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');  
        $db = $bootstrap->getResource('db');

        $userlist = $db->fetchAll(
             "SELECT w.userId,u.storeno,count(w.id) as num FROM uuch_waybill as w left join uuch_user as u on u.id = w.userId  where w.dateCreated >= '2016-01-01' and w.status != -1 group by w.userId order by num desc limit 0,500"
         );

        foreach ($userlist as $k => $value) {
            $userid = $value['userId'];
            $info = array();
             $sql = 
            $info[$k] = $db->fetchAll(
                    "SELECT DATE_FORMAT(w.dateCreated,'%Y-%m') AS month,count(w.id) as num,SUM(w.lastMoney) as money FROM uuch_waybill as w where w.userId = $userid and w.dateCreated >= '2016-01-01' and w.status != -1 group by month order by month desc"                     );

            //echo "SELECT DATE_FORMAT(w.dateCreated,'%Y-%m') AS month,count(w.id) as num,SUM(w.lastMoney) as money,count(o.id) as num2,SUM(o.sum) as money2 FROM uuch_waybill as w left join uuch_order as o on o.userId = w.userId where w.userId = $userid and w.dateCreated >= '2016-01-01' and w.status != -1 group by month order by month desc";
            $str = "";
            $str .= "<table style='margin-bottom: 10px;border-bottom: 1px solid red;padding-bottom: 10px'><tr><td>库号：".$value['storeno']."<br>发单总数：".$value['num']."</td>";
           foreach ($info[$k] as $values) {
               $str .= "<td style='border: 1px solid red;padding: 0 10px'><p>".$values['month']."</p><p>发单数：".$values['num']."</p><p>运单金额：".$values['money']."</p>";

           }
            $str .= "</tr></table>";
           echo $str;
        }
        //var_dump($info);exit;
        exit; 
    }


}